<template>
  <div class="department-edit-dialog">
    <!-- 弹窗标题 -->
    <div class="dialog-header">
      <h2>{{ isSubDepartment ? '新增下级科室' : '新增科室' }}</h2>
      <button class="close-btn" @click="handleCancel">×</button>
    </div>

    <!-- 表单内容 -->
    <el-form
      ref="departmentFormRef"
      :model="departmentForm"
      :rules="departmentRules"
      label-width="100px"
      class="department-form"
    >
      <el-form-item label="科室名称" prop="name">
        <el-input v-model="departmentForm.name" placeholder="请输入..." />
      </el-form-item>

      <el-form-item label="上级分类" prop="parentId">
        <el-select v-model="departmentForm.parentId" placeholder="请选择..." :disabled="isSubDepartment">
          <el-option v-for="item in parentDepartments" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <div class="tips-text">{{ isSubDepartment ? '新增下级科室时，上级分类不可修改' : '不选择分类默认为顶级分类' }}</div>
      </el-form-item>

      <el-form-item label="备注" prop="description">
        <el-input
          v-model="departmentForm.description"
          type="textarea"
          rows="4"
          placeholder="请输入备注"
          @input="handleDescriptionInput"
          :maxlength="200"
        />
        <div class="char-count">还可以输入{{ remainingChars }}个字</div>
      </el-form-item>

      <el-form-item label="是否显示" prop="status">
        <div class="radio-group">
          <el-radio v-model="departmentForm.status" label="是">是</el-radio>
          <el-radio v-model="departmentForm.status" label="否">否</el-radio>
        </div>
      </el-form-item>

      <el-form-item>
        <div class="form-actions">
          <el-button type="primary" class="confirm-btn" @click="handleSubmit">确定</el-button>
          <el-button class="cancel-btn" @click="handleCancel">取消</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElForm } from 'element-plus'
import { departmentApi } from '@/api/index'

/**
 * 智慧医疗系统 - 科室编辑弹窗
 * 功能：新增或编辑科室的基本信息
 */

// 路由相关
const route = useRoute()
const router = useRouter()
const hospitalId = Number(route.params.hospitalId)
const departmentId = Number(route.params.id)
const isEdit = !!departmentId
const parentId = route.query.parentId ? Number(route.query.parentId) : undefined
const isSubDepartment = !!parentId

// 表单引用
const departmentFormRef = ref<InstanceType<typeof ElForm>>()

// 响应式数据
const departmentForm = reactive<{
  id?: number
  hospitalId: number
  name: string
  parentId?: number
  status: string
  description?: string
}>({
  hospitalId: hospitalId,
  name: '',
  parentId: parentId,
  status: '是',
  description: ''
})

const parentDepartments = ref<{
  id: number
  name: string
}[]>([])

const loading = ref(false)

// 计算属性：剩余可输入字符数
const remainingChars = computed(() => {
  const maxLength = 200
  const currentLength = departmentForm.description?.length || 0
  return maxLength - currentLength
})

// 表单规则
const departmentRules = {
  name: [
    { required: true, message: '请输入科室名称', trigger: 'blur' },
    { max: 50, message: '科室名称不能超过50个字符', trigger: 'blur' }
  ],
  status: [{ required: true, message: '请选择科室状态', trigger: 'change' }]
}

// 生命周期
onMounted(() => {
  if (isEdit) {
    loadDepartmentDetail()
  } else {
    // 新增科室时，加载一级科室作为可选的上级科室
    loadParentDepartments()
  }
})

/**
 * 处理备注输入事件
 */
const handleDescriptionInput = () => {
  // 限制最大长度
  if (departmentForm.description && departmentForm.description.length > 200) {
    departmentForm.description = departmentForm.description.substring(0, 200)
  }
}

/**
 * 加载科室详情
 */
const loadDepartmentDetail = async () => {
  loading.value = true
  try {
    const response = await departmentApi.getDetail(departmentId)
    if (response.code === 200) {
      const data = response.data
      departmentForm.id = data.id
      departmentForm.name = data.name
      departmentForm.parentId = data.parentId
      departmentForm.status = data.status === '显示' ? '是' : '否'
      departmentForm.description = data.description

      // 加载上级科室列表
      loadParentDepartments()
    } else {
      ElMessage.error('获取科室详情失败')
    }
  } catch (error) {
    console.error('加载科室详情出错:', error)
    ElMessage.error('加载科室详情失败，请重试')
  } finally {
    loading.value = false
  }
}

/**
 * 加载上级科室列表
 */
const loadParentDepartments = async () => {
  try {
    const params = {
      hospitalId,
      currentPage: 1,
      pageSize: 100
    }

    const response = await departmentApi.getList(params)
    if (response.code === 200) {
      parentDepartments.value = response.data.items
    } else {
      ElMessage.error('获取上级科室列表失败')
    }
  } catch (error) {
    console.error('加载上级科室列表出错:', error)
    ElMessage.error('加载上级科室列表失败，请重试')
  }
}

/**
 * 提交表单
 */
const handleSubmit = async () => {
  if (!departmentFormRef.value) return

  try {
    const valid = await departmentFormRef.value.validate()
    if (valid) {
      loading.value = true

      // 准备提交数据
      const submitData = {
        ...departmentForm,
        status: departmentForm.status === '是' ? '显示' : '隐藏'
      }

      if (isEdit) {
        // 编辑科室
        const response = await departmentApi.update(submitData)
        if (response.code === 200) {
          ElMessage.success('科室更新成功')
          router.push({
            path: `/content/hospital/${hospitalId}/departments`
          })
        } else {
          ElMessage.error(response.message || '科室更新失败')
        }
      } else {
        // 新增科室
        const response = await departmentApi.add(submitData)
        if (response.code === 200) {
          ElMessage.success('科室新增成功')
          router.push({
            path: `/content/hospital/${hospitalId}/departments`
          })
        } else {
          ElMessage.error(response.message || '科室新增失败')
        }
      }
    }
  } catch (error) {
    console.error('提交表单出错:', error)
    ElMessage.error('提交失败，请重试')
  } finally {
    loading.value = false
  }
}

/**
 * 取消操作
 */
const handleCancel = () => {
  router.back()
}
</script>

<style lang="scss" scoped>
.department-edit-dialog {
  width: 500px;
  padding: 20px;
  box-sizing: border-box;

  .dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;

    h2 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
    }

    .close-btn {
      background: none;
      border: none;
      font-size: 20px;
      cursor: pointer;
      color: #999;

      &:hover {
        color: #333;
      }
    }
  }

  .department-form {
    width: 100%;
  }

  .tips-text {
    margin-top: 5px;
    font-size: 12px;
    color: #999;
  }

  .char-count {
    margin-top: 5px;
    font-size: 12px;
    color: #999;
    text-align: right;
  }

  .radio-group {
    display: flex;
    gap: 20px;
  }

  .form-actions {
    display: flex;
    justify-content: center;
    margin-top: 30px;

    button {
      width: 100px;
      margin: 0 15px;
    }

    .confirm-btn {
      background-color: #1890ff;
      border-color: #1890ff;
    }

    .cancel-btn {
      background-color: #fff;
      border-color: #d9d9d9;
      color: #666;
    }
  }
}
</style>